package com.sweets.look.ui.activity;

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebIconDatabase;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bilibili.magicasakura.utils.ThemeUtils;
import com.sweets.look.R;
import com.sweets.look.adapter.HistoryItem;
import com.sweets.look.adapter.SearchAdapter;
import com.sweets.look.constant.Constants;
import com.sweets.look.constant.JS;
import com.sweets.look.database.ClickHandler;
import com.sweets.look.database.DatabaseHandler;
import com.sweets.look.preference.PreferenceManager;
import com.sweets.look.receiver.BrowserBroadcastReceiver;
import com.sweets.look.task.ScreenshotTask;
import com.sweets.look.ui.App;
import com.sweets.look.ui.BaseActivity;
import com.sweets.look.ui.browser.BookmarkManager;
import com.sweets.look.ui.page.PageManager;
import com.sweets.look.ui.setting.GeneralSettings;
import com.sweets.look.ui.view.BrowserView;
import com.sweets.look.ui.view.FastView;
import com.sweets.look.ui.widget.MarkDialog;
import com.sweets.look.ui.widget.MarkEditDialog;
import com.sweets.look.ui.widget.MarkRadioDialog;
import com.sweets.look.ui.widget.MarkSheetMenu;
import com.sweets.look.ui.widget.MarkSheetMenu.OnSheetItemClickListener;
import com.sweets.look.ui.widget.MarkSlidingView;
import com.sweets.look.ui.widget.supertoast.SuperActivityToast;
import com.sweets.look.util.BrowserUtils;
import com.sweets.look.util.IntentUtils;
import com.sweets.look.util.LogUtils;
import com.sweets.look.util.Utils;
import com.sweets.look.util.ViewHelper;
import com.sweets.look.util.ViewUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class BrowserActivity extends BaseActivity {
    private ViewGroup rootLayout;
    private LinearLayout mTabWindow;

    class FullscreenHolder extends FrameLayout {
        public FullscreenHolder(Context ctx) {
            super(ctx);
            this.setBackgroundColor(ctx.getResources().getColor(android.R.color.black));//17170444
        }
    }

    class VideoCompletionListener implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
            onHideCustomView();
        }

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            return false;
        }
    }

    private final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(-1, -1);
    private ValueCallback<Uri[]> filePathCallback;
    private Activity mActivity;
    private final ColorDrawable mBackground = new ColorDrawable();
    private List<HistoryItem> mBookmarkList;
    private BookmarkManager mBookmarkManager;
    private Animation mBottomTransIn;
    private Animation mBottomTransOut;
    private BroadcastReceiver mBroadcastReceiver;
    private FrameLayout mBrowserFrame;
    private ClickHandler mClickHandler;
    private Context mContext;
    private BrowserView mCurrentView;
    private View mCustomView;
    private WebChromeClient.CustomViewCallback mCustomViewCallback;
    private DatabaseHandler mDatabaseHandler;
    private Bitmap mDefaultVideoPoster;
    private Animation mFadeIn;
    private Animation mFadeOut;
    private ImageView mForward;
    private boolean mFullScreen;
    private FullscreenHolder mFullscreenContainer;
    private String mHomepage;
    private int mIdGenerator = 0;
    private List<Integer> mIdList = new ArrayList<>();
    private PopupWindow mMenu;
    private TextView mMenuImg;
    private TextView mMenuPC;
    private TextView mMenuScreenshot;
    private TextView mMenuSource;
    private TextView mMenuTranslate;
    private int mOriginalOrientation;
    private LinearLayout mPadBar;
    private ImageView mPadForward;
    private boolean mPadMode;
    private TextView mPadTab;
    private PreferenceManager mPreferences;
    private ProgressBar mProgressBar;
    private ImageView mMenuOrForward;
    private ImageView mSaveState;
    private AutoCompleteTextView mSearch;
    private SearchAdapter mSearchAdapter;
    private String mSearchText;
    private TextView mShade;
    private View mStatusBarView;
    private TextView mTabCount;
    private LinearLayout mTabLayout;
    private MarkSlidingView mToolBar;
    private Animation mTopTransIn;
    private Animation mTopTransOut;
    private int mTouchX = 0;
    private int mTouchY = 0;
    private ValueCallback<Uri> mUploadMessage;
    private RelativeLayout mUrlBar;
    private int mUrlBarHeight;
    private View mVideoProgressView;
    private VideoView mVideoView;
    private List<BrowserView> mWebViewList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewHelper.setTranslucentStatus(this);

        this.setContentView(R.layout.browser_main);
        this.mActivity = this;
        this.mContext = this;
        this.initializeBroadcast();
        this.initializePreferences();
        this.initialize();
        if (getIntent() != null) {
            handleNewIntent(this.getIntent());
        }

        Utils.requestPermission(this.mContext, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"});

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("");
        return super.onCreateOptionsMenu(menu);
    }

    public void onCreateWindow(boolean isUserGesture, Message resultMsg) {
        if (resultMsg != null) {
            this.newTab(true, "");
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(mCurrentView.getWebView());
            resultMsg.sendToTarget();

        }
    }

    @Override
    protected void onDestroy() {
        if (this.mDatabaseHandler != null && (this.mDatabaseHandler.isOpen())) {
            this.mDatabaseHandler.close();
        }

        this.unregisterReceiver(this.mBroadcastReceiver);
        super.onDestroy();
    }


    /**
     * 添加标签
     *
     * @param title
     * @param url
     */
    private void addBookmark(String title, String url) {
        if (title != null && url != null) {
            if (url.startsWith("file://")) {
                url = "http://";
                title = "";
            }

            new MarkEditDialog(this.mContext).builder()
                    .setTitle(this.getResources().getString(R.string.action_add_bookmark))
                    .setCanceledOnTouchOutside(false)
                    .setTitleHint(this.getResources().getString(R.string.hint_title), title)
                    .setMsgHint(this.getResources().getString(R.string.hint_url), url)
                    .setOtherHint(this
                            .getResources().getString(R.string.hint_folder), "", this.mBookmarkManager.getFolders())
                    .setPositiveButton(this.getResources().getString(R.string.action_ok), new MarkEditDialog.OnCustomDialogListener() {
                        @Override
                        public void back(String title, String url, String folder) {
                            if (mBookmarkManager.addBookmark(new HistoryItem(BrowserUtils
                                    .fixUrl(url), title, folder))) {
                                ViewUtils.showToast(rootLayout, getResources().getString(R.string.message_add_bookmark));
                                mSearchAdapter.refreshBookmarks();
                                mBookmarkList = mBookmarkManager.getBookmarks();
                                if (BrowserUtils.isBookmarkPage(mContext, BrowserActivity
                                        .this.mCurrentView.getUrl())) {
                                    openBookmarkPage(mCurrentView.
                                            getWebView(), "", true);
                                }
                            }
                        }
                    }).setNegativeButton(this.getResources().getString(R.string.action_no), null).show();
        }
    }

    /**
     * 添加到历史记录
     *
     * @param title
     * @param url
     */
    private void addItemToHistory(final String title, final String url) {
        Runnable runnable = new Runnable() {
            public void run() {
                try {
                    if (mDatabaseHandler == null) {
                        mDatabaseHandler = new DatabaseHandler(BrowserActivity.
                                this.mContext);
                    } else if (!mDatabaseHandler.isOpen()) {
                        mDatabaseHandler = new DatabaseHandler(BrowserActivity.
                                this.mContext);
                    }

                    mDatabaseHandler.visitHistoryItem(url, title);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
            }
        };
        if (url != null && !url.startsWith("file://")) {
            new Thread(runnable).start();//异步执行
        }
    }

    /**
     * 过滤广告
     *
     * @param view
     */
    public void blockAds(WebView view) {
        if (view != null && view.getUrl() != null && this.mPreferences.getAdBlockEnabled()
                && !view.getUrl().startsWith("file://")) {
            if (this.mDatabaseHandler == null) {
                this.mDatabaseHandler = new DatabaseHandler(this.mContext);
            } else if (!this.mDatabaseHandler.isOpen()) {
                this.mDatabaseHandler = new DatabaseHandler(this.mContext);
            }

            String tag = mDatabaseHandler.getMatchTag(BrowserUtils.getDomainName(view.getUrl()));
            if (TextUtils.isEmpty(tag) || tag.trim().isEmpty()) {
                return;
            }
            LogUtils.e(BrowserActivity.class.getSimpleName(), "blockAds: " +
                    "广告:" + tag);

            view.loadUrl(JS.deleteTags(tag));
            view.loadUrl(JS.runCustomCSS(tag + "{display: none !important}"));
        }
    }

    private void changeColor(int webColor) {
        int textColor = ViewUtils.isLightColor(webColor) ?
                this.getResources().getColor(R.color.app_color_dark) :
                this.getResources().getColor(android.R.color.white);//17170443
        ImageView[] allImage = new ImageView[6];
        allImage[0] = (ImageView) this.findViewById(R.id.titlebar_find);
        allImage[1] = (ImageView) this.findViewById(R.id.titlebar_go);
        allImage[2] = (ImageView) this.findViewById(R.id.pad_back);
        allImage[3] = (ImageView) this.findViewById(R.id.pad_forward);
        allImage[4] = (ImageView) this.findViewById(R.id.tab_bg);
        allImage[5] = (ImageView) this.findViewById(R.id.pad_options);
        ViewUtils.setImageTint(textColor, allImage);
        ((TextView) this.findViewById(R.id.pad_tab)).setTextColor(textColor);
        this.mSearch.setTextColor(textColor);
        this.mSearch.setHintTextColor(textColor);
        ArgbEvaluator argbEvaluator = new ArgbEvaluator();
        Object[] object = new Object[2];
        object[0] = this.mBackground.getColor();
        object[1] = webColor;

        final boolean isLight = ViewUtils.isLightColor(webColor);

        ValueAnimator animator = ValueAnimator.ofObject(argbEvaluator, object);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int animatedValue = (int) animation.getAnimatedValue();
                int statusColor = animatedValue;
                mBackground.setColor(animatedValue);
                mUrlBar.setBackgroundColor(animatedValue);
                mActivity.getWindow().setBackgroundDrawable(new ColorDrawable(animatedValue));
                if (Constants.API >= 19 && !mPreferences.getHideStatusBarEnabled()) {
                    if (Build.VERSION.SDK_INT >= 21) {
                        if (isLight) {
                            statusColor = ViewUtils.mixTwoColors(mActivity.getResources()
                                    .getColor(R.color.app_color_dark), animatedValue, 0.2f);//17170444
                        }

                        getWindow().setStatusBarColor(statusColor);
                    } else {
                        if (mStatusBarView != null) {
                            mStatusBarView.setVisibility(isLight ? View.VISIBLE : View.GONE);
                        }

                    }
                }
            }
        });
        animator.setDuration(300);
        animator.start();
    }

    /**
     * 拷贝链接
     *
     * @param id
     */
    public synchronized void copyTagLink(int id) {
        int which = this.mIdList.indexOf(id);
        if (which != -1 && this.mWebViewList.get(which).getUrl() != null && !this.mWebViewList.get(which).
                getUrl().startsWith("file://")) {
            BrowserUtils.copyURL(this.mContext, this.mWebViewList.get(which).getUrl());
        }
    }

    /**
     * 删除所有tab页
     */
    private synchronized void deleteAllTab() {
        if (this.mWebViewList == null) {
            return;
        }
        if (this.mWebViewList.size() == 1) {
            return;
        }
        int i = this.mWebViewList.size() - 1;
        while (i >= 0) {
            this.deleteTab(this.mWebViewList.get(i).getId());
            --i;
        }
        this.touchShade();

    }


    private synchronized void deleteFolder(final String ex_folder) {

        new MarkDialog(this.mContext).builder().setTitle(this.getResources().getString(R.string.msg_delete_folder))
                .setMessage(this.getResources().getString(R.string.cannot_undo)).setPositiveButton(this.getResources()
                .getString(R.string.action_ok), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBookmarkManager.renameFolder(ex_folder, "");
                openBookmarkPage(mCurrentView.getWebView(),
                        null, true);
                mBookmarkList = mBookmarkManager.getBookmarks();
            }
        }).setNegativeButton(this.getResources().getString(R.string.action_no), null).show();

    }


    private synchronized void newTab(boolean show, String url) {
        BrowserView webview = new BrowserView(this.mActivity, url);
        mWebViewList.add(webview);
        webview.setId(mIdGenerator);
        mIdList.add(mIdGenerator);
        ++mIdGenerator;
        if (show) {
            if (this.mCurrentView != null) {
                this.mBrowserFrame.removeView(this.mCurrentView.getMainView());
                this.mCurrentView.deactivateTab();
            }

            this.mCurrentView = webview;
            this.mCurrentView.activateTab();
            if (this.mCurrentView != null) {
                this.mCurrentView.requestFocus();
            }

            this.updateProgress(webview.getProgress());
            this.updateUrlBox(webview.getUrl(), webview.getTitle(), false,
                    false);
            mBrowserFrame.addView(webview.getMainView());
            webview.setVisible();
        } else {
            webview.deactivateTab();
        }

        mTabLayout.addView(webview.getTabView());
        this.touchShade();
        if (this.mWebViewList.size() <= 99) {
            this.mTabCount.setText(String.valueOf(this.mWebViewList.size()));
            this.mPadTab.setText(String.valueOf(this.mWebViewList.size()));
        } else {
            this.mTabCount.setText(":)");
            this.mPadTab.setText(":)");
        }
    }


    /**
     * @param id
     */
    public synchronized void deleteTab(int id) {
        mTabLayout.clearDisappearingChildren();
        int deleteId = this.mIdList.indexOf(id);
        int currentId = this.mIdList.indexOf(this.mCurrentView.getId());
        BrowserView browserView = this.mWebViewList.get(deleteId);
        if (deleteId >= this.mWebViewList.size()) {
            return;
        }

        if (deleteId != -1 && currentId != -1 && browserView != null) {
            if (currentId > deleteId) {

                if (browserView.isShown()) {
                    this.showTab(this.mWebViewList.get(deleteId - 1));
                }
            } else {
                if (this.mWebViewList.size() > deleteId + 1) {
                    if (browserView.isShown()) {
                        this.showTab(this.mWebViewList.get(deleteId + 1));
                    }
                } else if (this.mWebViewList.size() <= 1) {
                    this.newTab(true, null);
                } else if (browserView.isShown()) {
                    this.showTab(this.mWebViewList.get(deleteId - 1));
                }
            }


            mTabLayout.removeView(this.mWebViewList.get(deleteId).getTabView());
            browserView.onDestroy();
            mWebViewList.remove(deleteId);
            mIdList.remove(deleteId);
            mTabCount.setText(String.valueOf(this.mWebViewList.size()));
            mPadTab.setText(String.valueOf(this.mWebViewList.size()));

        }
    }

    private void doNext(int requestCode, int[] grantResults, final String[] permissions) {
        if (requestCode == 111 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            new MarkDialog(this.mContext).builder()
                    .setTitle(this.getResources().getString(R.string.dialog_message))
                    .setMessage(this.getResources().getString(R.string.need_permission))
                    .setCanceledOnTouchOutside(false)
                    .setPositiveButton(this.getResources().getString(R.string.action_ok), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Utils.requestPermission(mContext, permissions);
                        }
                    }).show();
        }
    }


    private synchronized void editBookmark(String url) {
        final int loc = this.getBookmarkIdFromUrl(url);
        if (loc != -1) {
            new MarkEditDialog(this.mContext).builder()
                    .setTitle(this.getResources().getString(R.string.title_edit_bookmark))
                    .setCanceledOnTouchOutside(true)
                    .setTitleHint(this.getResources().getString(R.string.hint_title), this.mBookmarkList.get(loc).getTitle())
                    .setMsgHint(this.getResources()
                            .getString(R.string.hint_url), this.mBookmarkList.get(loc).getUrl())
                    .setOtherHint(this.getResources().getString(R.string.hint_folder), this.mBookmarkList.get(loc).getFolder(),
                            this.mBookmarkManager.getFolders())
                    .setPositiveButton(this.getResources().getString(
                            R.string.action_ok), new MarkEditDialog.OnCustomDialogListener() {
                        @Override
                        public void back(String title, String msg, String folder) {
                            mBookmarkList.get(loc).setTitle(title);
                            mBookmarkList.get(loc).setUrl(BrowserUtils.fixUrl(
                                    msg));
                            mBookmarkList.get(loc).setFolder(folder);
                            mBookmarkManager.overwriteBookmarks(BrowserActivity.this
                                    .mBookmarkList);
                            openBookmarkPage(mCurrentView.getWebView(), null, true);
                        }
                    }).show();
        }


    }

    /**
     * 进入电脑模式
     */
    private void enterPadMode() {
        this.mPadMode = false;
        if (this.mCurrentView != null) {
            this.mPadMode = true;
            if (this.findViewById(R.id.pad_pannel).getVisibility() != View.VISIBLE) {
                this.findViewById(R.id.pad_pannel).setVisibility(View.VISIBLE);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(Math.min(ViewUtils.
                                convertToDensityPixels(this.mContext, 240),
                        ViewUtils.getWindowWidth(this.mContext) - 300), -2);
                layoutParams.addRule(3, R.id.urlBar);
                layoutParams.addRule(11);
//                mTabScrollView.setLayoutParams(layoutParams);
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(0, 0);
                lp.addRule(12);//12
                mToolBar.setLayoutParams(lp);
                mSearch.setTextSize(2, 16f);
                mSearch.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.et_bg));
            }
        }
    }

    /**
     * 退出
     */
    private void exit() {
        if ((this.mPreferences.getRestoreLostTabsEnabled())
                && !this.mPreferences.getIncognitoModeEnabled()) {
            this.saveOpenTabs();
        }

        if (this.mPreferences.getClearCacheExit()) {
            BrowserUtils.clearWebViewCache(this.mContext);
        }

        if (this.mPreferences.getClearFormdataExitEnabled()) {
            BrowserUtils.clearWebViewFormData(this.mContext);
        }

        if (this.mPreferences.getClearHistoryExitEnabled()) {
            BrowserUtils.clearWebViewHistory(this.mContext);
        }

        if (this.mPreferences.getClearCookiesExitEnabled()) {
            BrowserUtils.clearWebViewCookies(this.mContext);
        }

        if (this.mPreferences.getClearWebStorageExitEnabled()) {
            BrowserUtils.clearWebStorage();
        }

        for (int i = 0; i < this.mWebViewList.size(); i++) {
            if (this.mWebViewList.get(i) != null) {
                this.mWebViewList.get(i).onDestroy();
            }
        }

        this.mCurrentView = null;
        this.mWebViewList.clear();
        this.finish();
    }

    /**
     * 退出平板模式
     */
    private void exitPadMode() {
        if (this.mPreferences.getUIChoice() != 2) {
            this.mPadMode = false;
            if (this.mCurrentView != null) {
                this.findViewById(R.id.pad_pannel).setVisibility(View.GONE);
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, -2);
                lp.addRule(2, R.id.toolBar);
//                this.mTabScrollView.setLayoutParams(lp);
                RelativeLayout.LayoutParams v1 = new RelativeLayout.LayoutParams(-1, this.mContext.getResources()
                        .getDimensionPixelSize(R.dimen.bottom_bar_height));
                v1.addRule(12);
                this.mToolBar.setLayoutParams(v1);
                this.mSearch.setTextSize(2, 18f);
                this.mSearch.setBackgroundDrawable(this.getResources().getDrawable(android.R.color.transparent));//17170445
            }
        }
    }

    /**
     * 页内搜索
     */
    private void findInPage() {
        new MarkEditDialog(this.mContext).builder()
                .setTitle(this.getResources().getString(R.string.action_find))
                .setCanceledOnTouchOutside(true).setTitleHint("", "")
                .setPositiveButton(this.getResources().getString(R.string.search_hint),
                        new MarkEditDialog.OnCustomDialogListener() {
                            @Override
                            public void back(String title, String msg, String other) {
                                if (mCurrentView != null) {
                                    mCurrentView.getWebView().showFindDialog(title, true);
                                }
                            }
                        }).show();
    }

    public Activity getActivity() {
        return this.mActivity;
    }

    private static String[] getArray(String input) {
        return input.split("\\|\\$\\|SEPARATOR\\|\\$\\|");
    }

    private int getBookmarkIdFromUrl(String url) {
        int i = 0;
        int size = this.mBookmarkList.size();
        while (true) {
            if (i >= size) {
                return -1;
            } else if (!this.mBookmarkList.get(i).getUrl().equals(url)
                    && !(this.mBookmarkList.get(i).getUrl() + "/").equals(url)) {
                ++i;
                continue;
            }

            return i;
        }

    }

    public Bitmap getDefaultVideoPoster() {
        if (this.mDefaultVideoPoster == null) {
            this.mDefaultVideoPoster = BitmapFactory.decodeResource(this.getResources(),
                    android.R.drawable.ic_media_play);//17301540
        }

        return this.mDefaultVideoPoster;
    }

    public String getInfo(int what) {
        return "";
    }


    /**
     * 获得状态栏高度
     *
     * @param context
     * @return
     */
    private static int getStatusBarHeight(Context context) {
        return context.getResources().getDimensionPixelSize(context.getResources()
                .getIdentifier("status_bar_height", "dimen", "android"));
    }

    public void getTouch(int x, int y) {
        this.mTouchX = x;
        this.mTouchY = this.mUrlBar.getVisibility() == View.VISIBLE ? y : y - this.mUrlBarHeight;
    }

    @SuppressLint(value = {"InflateParams"})
    public View getVideoLoadingProgressView() {
        if (this.mVideoProgressView == null) {
            this.mVideoProgressView = LayoutInflater.from(this.mContext)
                    .inflate(R.layout.browser_video_loading, null);
        }

        return this.mVideoProgressView;
    }

    /**
     * 拷贝网页内容
     *
     * @param text
     */
    public void getWebText(final String text) {
        this.runOnUiThread(new Runnable() {
            public void run() {
                BrowserUtils.copyText(mContext, text);
            }
        });
    }

    /**
     * 返回
     */
    private void goBack() {
        if (this.mTabWindow.getVisibility() == View.VISIBLE) {
            this.touchShade();
            return;
        }
        if (this.mCurrentView != null && (this.mCurrentView.canGoBack())) {
            mCurrentView.goBack();
            return;
        }
        if (this.mWebViewList != null && this.mWebViewList.size() > 1) {
            deleteTab(this.mCurrentView.getId());
            return;
        }

        exit();//退出
    }

    /**
     * 前进
     */
    private void goForward() {
        if (this.mCurrentView.getProgress() < 100) {
            this.mCurrentView.stopLoading();
            this.updateProgress(100);
        } else if (this.mCurrentView.canGoForward()) {
            this.mCurrentView.goForward();
        }
    }

    /**
     * 跳到首页
     */
    private void goHomePage() {
        mHomepage = this.mPreferences.getHomepage();
        if ((mHomepage.startsWith("about:home")) || (mHomepage.startsWith("about:links"))) {
            openDefaultHomepage(this.mCurrentView.getWebView());
        } else if (this.mHomepage.startsWith("about:bookmarks")) {
            openBookmarkPage(this.mCurrentView.getWebView(), null, false);
        } else {
            mCurrentView.loadUrl(this.mHomepage);
        }

        ViewUtils.hideView(this, mShade, this.mFadeOut);//隐藏背景阴影
        ViewUtils.hideView(this, mTabWindow, this.mBottomTransOut);
    }

    private void handleNewIntent(Intent intent) {
        if (intent == null)
            return;
        if (this.mCurrentView == null)
            this.initialize();

        if (intent.getBooleanExtra("cmd_search", false)) {
            App.getMainHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSearch.requestFocus();
                }
            }, 300);
            return;
        }
        if (intent.getBooleanExtra("cmd_bookmark", false)) {
            openBookmarkPage(this.mCurrentView.getWebView(), null, true);
            return;
        }

        if (intent.getBooleanExtra("cmd_scan", false)) {
            String msg = intent.getStringExtra("scan_msg");
            searchTheWeb(msg);
            return;
        }

        String extra = null;
        if (intent.hasExtra("OPEN")) {
            extra = intent.getStringExtra("OPEN");
        } else if (intent.hasExtra("query")) {
            extra = this.mSearchText + intent.getStringExtra("query");
        } else if (intent.getDataString() != null) {
            extra = intent.getDataString();
        }
        if (this.mCurrentView != null && extra != null && this.mCurrentView.getUrl() != null
                && (BrowserUtils.isSetedHomePage(this.mContext, this.mCurrentView.getUrl()))) {
            this.mCurrentView.loadUrl(extra);
            return;
        }
        if (extra != null) {
            newTab(true, extra);
        }

    }

    /**
     * 隐藏操作栏
     */
    public void hideOperationBar() {
        if (this.mUrlBar.getVisibility() != View.GONE && (this.mFullScreen)) {
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(this.mBrowserFrame,
                    "translationY", new float[]{this.mUrlBarHeight, 0f});
            if (this.mPreferences.getAnimEnabled()) {
                objectAnimator.setDuration(this.mContext.getResources()
                        .getInteger(R.integer.anim_time));
            } else {
                objectAnimator.setDuration(0);
            }

            objectAnimator.setInterpolator(new AccelerateInterpolator());
            objectAnimator.start();
            ViewUtils.hideView(this, mUrlBar, mTopTransOut);
            ViewUtils.hideView(this, mToolBar, mBottomTransOut);
        }
    }

    /**
     * 初始化菜单
     */
    private void initMenu() {
        if (this.mMenu == null) {
            this.mMenu = new PopupWindow(this.mContext);
            View menuView = ((LayoutInflater) this.mContext.getSystemService(LAYOUT_INFLATER_SERVICE))
                    .inflate(R.layout.browser_menu, (ViewGroup) this.mActivity
                            .findViewById(android.R.id.content), false);//16908290
            this.mMenu.setContentView(menuView);
            this.mMenuTranslate = (TextView) menuView.findViewById(R.id.action_translate);
            this.mMenuScreenshot = (TextView) menuView.findViewById(R.id.action_screenshot);
            this.mMenuSource = (TextView) menuView.findViewById(R.id.action_source);
            this.mMenuPC = (TextView) menuView.findViewById(R.id.action_pcview);
            this.mMenuImg = (TextView) menuView.findViewById(R.id.action_image_off);

            menuView.findViewById(R.id.action_share)
                    .setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View view) {
                            installShortcut(mCurrentView.getTitle(),
                                    mCurrentView.getUrl());
                            mMenu.dismiss();
                            return true;
                        }
                    });
            menuView.setFocusableInTouchMode(true);
            menuView.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_MENU) {//82
                        if (!mMenu.isShowing()) {
                            return false;
                        } else {
                            mMenu.dismiss();
                            return true;
                        }
                    }
                    return false;
                }
            });
            int width = ViewUtils.measureTextViewWidth(this.mContext,
                    this.getString(R.string.image_auto), 16) +
                    ViewUtils.convertToDensityPixels(this.mContext, 40);
            if (width < ViewUtils.convertToDensityPixels(this.mContext, 150)) {
                width = ViewUtils.convertToDensityPixels(this.mContext, 150);
            }

            this.mMenu.setWidth(width);
            this.mMenu.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);//-2
            this.mMenu.setFocusable(true);
            this.mMenu.setOutsideTouchable(true);
            this.mMenu.update();
            this.mMenu.setBackgroundDrawable(new BitmapDrawable());
//          this.mMenu.setBackgroundDrawable(this.getResources().getDrawable(android.R.color.transparent));//17170445
            this.mMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    setWebViewForwardColor();
                    ViewUtils.dimBackground(BrowserActivity.this, 0.5f, 1.0f);
                }
            });
        }
        mMenuScreenshot.setVisibility(mPreferences.getAddonsScreenshotEnabled() ?
                View.VISIBLE : View.GONE);

        mMenuSource.setVisibility(mPreferences.getAddonsViewSourceEnabled() ?
                View.VISIBLE : View.GONE);

        mMenuTranslate.setVisibility(mPreferences.getAddonsTranslateEnabled() ?
                View.VISIBLE : View.GONE);
        ViewUtils.setTextActive(this.mContext, this.mMenuPC,
                this.mPreferences.getRuequstDesktopSiteEnabled());

        String imageSwitch;
        if (mPreferences.getImageSwitchEnabled()) {
            imageSwitch = this.getResources().getString(R.string.image_auto);
        } else if (mPreferences.getBlockImagesEnabled()) {
            imageSwitch = this.getResources().getString(R.string.image_on);
        } else {
            imageSwitch = this.getResources().getString(R.string.image_off);
        }

        mMenuImg.setText(imageSwitch);
        if (this.mPreferences.getAnimEnabled()) {
            this.mMenu.setAnimationStyle(R.style.MenuAnimation);
        } else {
            this.mMenu.setAnimationStyle(R.style.NullAnimation);
        }

    }

    private synchronized void initialize() {
        rootLayout = (ViewGroup) findViewById(R.id.root_layout);

        this.mClickHandler = new ClickHandler(this.mContext);
        this.mBookmarkManager = new BookmarkManager(this.mContext);
        this.mTabCount = (TextView) this.findViewById(R.id.toolbar_tab);
        this.mPadTab = (TextView) this.findViewById(R.id.pad_tab);
        this.mShade = (TextView) this.findViewById(R.id.webview_shade);
        this.mTabLayout = (LinearLayout) this.findViewById(R.id.TabLayout);
        this.mBrowserFrame = (FrameLayout) this.findViewById(R.id.holder);
        this.mTabWindow = (LinearLayout) findViewById(R.id.tabWindow);

        this.mSearch = (AutoCompleteTextView) this.findViewById(R.id.enterUrl);
        this.mProgressBar = (ProgressBar) this.findViewById(R.id.progressBar);
        this.mForward = (ImageView) this.findViewById(R.id.toolbar_forward);
        this.mPadForward = (ImageView) this.findViewById(R.id.pad_forward);
        this.mSaveState = (ImageView) this.findViewById(R.id.titlebar_find);
        this.mUrlBar = (RelativeLayout) this.findViewById(R.id.urlBar);
        this.mToolBar = (MarkSlidingView) this.findViewById(R.id.toolBar);
        this.mPadBar = (LinearLayout) this.findViewById(R.id.pad_pannel);
        this.mFadeIn = AnimationUtils.loadAnimation(this.getApplicationContext(), R.anim.fade_in);
        this.mFadeOut = AnimationUtils.loadAnimation(this.getApplicationContext(), R.anim.fade_out);
        this.mBottomTransIn = AnimationUtils.loadAnimation(this.getApplicationContext(), R.anim.bottom_trans_in);
        this.mBottomTransOut = AnimationUtils.loadAnimation(this.getApplicationContext(), R.anim.bottom_trans_out);
        this.mTopTransIn = AnimationUtils.loadAnimation(this.getApplicationContext(), R.anim.top_trans_in);
        this.mTopTransOut = AnimationUtils.loadAnimation(this.getApplicationContext(), R.anim.top_trans_out);
        this.mMenuOrForward = (ImageView) this.findViewById(R.id.titlebar_go);
        if (this.mWebViewList != null) {
            this.mWebViewList.clear();
        } else {
            this.mWebViewList = new ArrayList<>();
        }

        if (this.mIdList != null) {
            this.mIdList.clear();
        } else {
            this.mIdList = new ArrayList<>();
        }

        this.mHomepage = this.mPreferences.getHomepage();
        this.mToolBar.setOnMenuOpenListener(new MarkSlidingView.OnMenuOpenListener() {
            @Override
            public void onMenuOpen(int flag) {
                if (flag == 0) {
                    operation(mPreferences.getGestureToolbarLeftChoice());
                } else if (flag == 1) {
                    operation(mPreferences.getGestureToolbarRightChoice());
                }
            }
        });
        this.mSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && mCurrentView != null) {
                    mMenuOrForward.setImageResource(R.drawable.toolbar_menu);
                    if (mCurrentView != null) {
                        if (mCurrentView.getProgress() < 100) {
                            setIsLoading();
                        } else {
                            setIsFinishedLoading();
                        }
                    }

                    updateUrlBox(mCurrentView.getUrl(), mCurrentView.getTitle(), false,
                            false);
                    ViewUtils.showView(BrowserActivity.this, mToolBar, mBottomTransIn);
                    setWebViewForwardColor();
                    if (mPreferences.getSearchTimes() > mPreferences.getLinksTimes() + 3) {
                        mSearch.setInputType(1);
                    }

                    if (!mPadMode) {
                        return;
                    }

                    mPadBar.setVisibility(View.VISIBLE);
                    mSearch.setBackgroundResource(R.drawable.et_bg);
                    mSearch.setTextSize(2, 16f);
                    return;
                }

                if (hasFocus) {
                    mMenuOrForward.setImageResource(R.drawable.toolbar_forward);
                    ViewUtils.hideView(BrowserActivity.this, mTabWindow, null);
                    updateUrlBox(mCurrentView.getUrl(), mCurrentView.getTitle(), true, false);
                    ViewUtils.hideView(BrowserActivity.this, mToolBar, null);
                    if (mSearch.getText().toString().trim().length() > 0) {
                        mSearch.selectAll();
                    }

                    operateIME(0);
                    setWebViewForwardColor();
                    if (!mPadMode) {
                        return;
                    }

                    mPadBar.setVisibility(View.GONE);
                    mSearch.setBackgroundResource(android.R.color.transparent);//17170445
                    mSearch.setTextSize(2, 18f);
                }
            }
        });
        this.mSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_ENTER: {//66
                        operateIME(1);
                        searchTheWeb(BrowserActivity.this.mSearch.getText().toString().trim());
                        if (mCurrentView != null) {
                            mCurrentView.requestFocus();
                        }
                        break;
                    }
                    case KeyEvent.KEYCODE_MENU: {//82
                        break;
                    }
                    default: {
                        return false;
                    }
                }
                return true;
            }
        });
        if (this.mDatabaseHandler == null) {
            this.mDatabaseHandler = new DatabaseHandler(this.mContext);
        } else if (!this.mDatabaseHandler.isOpen()) {
            this.mDatabaseHandler = new DatabaseHandler(this.mContext);
        }

        if (Constants.API < 19) {
            WebIconDatabase.getInstance().open(this.getDir("icons", 0).getPath());
        }

        this.mBackground.setColor(((ColorDrawable) this.mUrlBar.getBackground()).getColor());
        this.initializeSearchSuggestions(this.mSearch);
        this.initializeTabs();
        this.initMenu();
        this.initializeWidgetPreferences();
        this.initializeAfterOpened();
    }


    /**
     *
     */
    private synchronized void initializeAfterOpened() {

        this.findViewById(R.id.action_new_tab)
                .setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        BrowserActivity.this.deleteAllTab();
                        return true;
                    }
                });
        this.findViewById(R.id.toolbar_back)
                .setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        BrowserActivity.this.operation(BrowserActivity.this.mPreferences.getKeyBackChoice());
                        return true;
                    }
                });
        this.findViewById(R.id.pad_back)
                .setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        operation(mPreferences.getKeyBackChoice());
                        return true;
                    }
                });
        this.mForward.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                operation(mPreferences.getKeyForwardChoice());
                return true;
            }
        });
        this.mPadForward.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                operation(mPreferences.getKeyForwardChoice());
                return true;
            }
        });
        this.findViewById(R.id.toolbar_home).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                operation(mPreferences.getKeyHomeChoice());
                return true;
            }
        });
        this.mTabCount.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                operation(mPreferences.getKeyTabChoice());
                return true;
            }
        });
        this.mPadTab.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                operation(mPreferences.getKeyTabChoice());
                return true;
            }
        });
        this.findViewById(R.id.titlebar_go).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                operation(mPreferences.getKeyMenuChoice());
                return true;
            }
        });
        this.findViewById(R.id.pad_options).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                operation(mPreferences.getKeyMenuChoice());
                return true;
            }
        });
        if (Utils.getAppVersionCode(this.mContext) <= this.mPreferences.getChangelogCode()) {
            return;
        }

//      this.mCurrentView.loadUrl(PageManager.getAboutPage(this.mContext));
        this.mPreferences.setChangelogCode(Utils.getAppVersionCode(this.mContext));

    }

    private void initializeBroadcast() {
        this.mBroadcastReceiver = new BrowserBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        intentFilter.addAction("android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED");
        intentFilter.addAction("android.intent.action.DOWNLOAD_COMPLETE");
        this.registerReceiver(this.mBroadcastReceiver, intentFilter);
    }

    private synchronized void initializePreferences() {
        this.mPreferences = PreferenceManager.getInstance();
        this.mFullScreen = this.mPreferences.getFullScreenEnabled();
        if (this.mPreferences.getHideStatusBarEnabled()) {//全屏幕
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            ViewHelper.setStatusBarTintColor(this, ThemeUtils.getColorById(this, R.color.theme_color_primary));
            this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        //搜索引擎初始化
        switch (this.mPreferences.getSearchChoice()) {
            case 0: {
                this.mSearchText = this.mPreferences.getSearchUrl();
                if (!this.mSearchText.startsWith("http://")) {
                    if (this.mSearchText.startsWith("https://")) {
                    } else {
                        this.mSearchText = Constants.BAIDU_SEARCH;
                    }
                }
                break;
            }
            case 1: {
                this.mSearchText = Constants.BAIDU_SEARCH;
                break;
            }
            case 2: {
                this.mSearchText = Constants.GOOGLE_SEARCH;
                break;
            }
            case 3: {
                this.mSearchText = Constants.BING_SEARCH;
                break;
            }
            case 4: {
                this.mSearchText = Constants.SHENMA_SEARCH;
                break;
            }
            case 5: {
                this.mSearchText = Constants.HAOSOU_SEARCH;
                break;
            }
            default: {
                this.mSearchText = Constants.BAIDU_SEARCH;
                break;
            }
        }

        switch (this.mPreferences.getScreenOrientation()) {
            case 1: {
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);//2
                break;
            }
            case 2: {
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);//10
                break;
            }
            case 3: {
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//1
                break;
            }
            case 4: {
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//0
                break;
            }
        }
        this.mPreferences.setOpenTimes(this.mPreferences.getOpenTimes() + 1);
        switch (this.mPreferences.getUIChoice()) {
            case 0: {
                if (ViewUtils.isTablet(this.mContext)) {
                    this.enterPadMode();
                } else {
                    this.exitPadMode();
                }
                break;
            }
            case 1: {
                this.exitPadMode();
                break;
            }
            case 2: {
                this.enterPadMode();
                break;
            }
        }
    }

    private synchronized void initializeSearchSuggestions(AutoCompleteTextView getUrl) {
        getUrl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView arg4, View arg1, int arg2, long arg3) {
                try {
                    searchTheWeb(((TextView) arg1.findViewById(R.id.url)).getText().toString());
                    operateIME(1);
                    if (mCurrentView != null) {
                        mCurrentView.requestFocus();
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        });
        getUrl.setSelectAllOnFocus(true);
        mSearchAdapter = new SearchAdapter(this.mContext);
        getUrl.setAdapter(this.mSearchAdapter);
        getUrl.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (!mSearch.hasFocus()) {
                    mSearch.requestFocus();
                }
                return false;
            }
        });
    }

    private synchronized void initializeTabs() {
        this.restoreOrNewTab();
    }

    private synchronized void initializeWidgetPreferences() {
        this.mUrlBarHeight = Constants.API < 19 || Constants.API >= 21 || (this.mPreferences.getHideStatusBarEnabled())
                ? this.mContext.getResources().getDimensionPixelSize(R.dimen.top_bar_height) : this.mContext
                .getResources().getDimensionPixelSize(R.dimen.top_bar_height) + BrowserActivity.getStatusBarHeight(
                this.mContext);
        this.mBrowserFrame.setKeepScreenOn(this.mPreferences.getWakeLockEnabled());
        if (!this.mPreferences.getColorModeEnabled() && !this.mPreferences.getNightModeEnabled()) {
            this.changeColor(this.getResources().getColor(R.color.theme_color_primary));
        }

        this.switchFullScreenMode();
        if (this.mPreferences.getSearchTimes() > this.mPreferences.getLinksTimes() + 3) {
            this.mSearch.setInputType(1);
        }
    }

    private void installShortcut(String title, String url) {
        Intent intent = new Intent(this.mContext, BrowserActivity.class);
        intent.setData(Uri.parse(url));
        intent.setFlags(276824064);//276824064
        Intent broadIntent = new Intent();
        broadIntent.putExtra("android.intent.extra.shortcut.ICON_RESOURCE",
                Intent.ShortcutIconResource.fromContext(this.mContext, R.drawable.ic_launcher));
        broadIntent.putExtra("android.intent.extra.shortcut.INTENT", intent);
        broadIntent.putExtra("android.intent.extra.shortcut.NAME", title);
        broadIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        this.sendBroadcast(broadIntent);
        ViewUtils.showToast(rootLayout, this.getResources().getString(R.string.toast_operation_done));
    }

    private void itemLongClick(final String url, int what) {

        MarkSheetMenu sheetMenu = new MarkSheetMenu(this.mContext).builder();
        sheetMenu.setFocusable(true);
        sheetMenu.setOutsideTouchable(true);
        if (what != Constants.LONG_CLICK_BOOKMARK_FOLDER) {//4
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_open_in_new), new MarkSheetMenu.OnSheetItemClickListener() {
                public void onClick(int which) {
                    newTab(false, url);
                }
            });
        }

        if (what != Constants.LONG_CLICK_BOOKMARK_FOLDER) {
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_copy), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    BrowserUtils.copyURL(mContext, url);
                }
            });
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_copy_text), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    if (mCurrentView != null) {
                        mCurrentView.loadUrl(JS.copyLinkText(url));
                    }
                }
            });
        }

        if (what == Constants.LONG_CLICK_IMG) {
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_save_img), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    BrowserUtils.downloadFile(mActivity, url, BrowserActivity
                            .this.mCurrentView.getUserAgent(), "attachment", "image/*", BrowserActivity
                            .this.mPreferences.getIncognitoModeEnabled(), null, true);
                }
            });
        } else if (what == Constants.LONG_CLICK_BOOKMARK) {
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_send_to_launcher), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    installShortcut(mBookmarkList.get(BrowserActivity
                            .this.getBookmarkIdFromUrl(url)).getTitle(), url);
                }
            });
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_edit), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    editBookmark(url);
                }
            });
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_delete), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    String v0 = mBookmarkList.get(getBookmarkIdFromUrl(
                            url)).getFolder();
                    if (mBookmarkManager.deleteBookmark(url)) {
                        mSearchAdapter.refreshBookmarks();
                        mBookmarkList = mBookmarkManager.getBookmarks();
                        openBookmarkPage(mCurrentView.getWebView(),
                                v0, true);
                        mBookmarkList = mBookmarkManager.getBookmarks();
                    }
                }
            });
        } else if (what == Constants.LONG_CLICK_BOOKMARK_FOLDER) {
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_edit), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    renameFolder(url);
                }
            });
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_delete), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    deleteFolder(url);
                }
            });
        } else if (what == Constants.LONG_CLICK_HOMEPAGE) {
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_edit), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    editBookmark(url);
                }
            });
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_delete), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    if (mBookmarkManager.deleteBookmark(url)) {
                        mSearchAdapter.refreshBookmarks();
                        mBookmarkList = mBookmarkManager.getBookmarks();
                        openDefaultHomepage(mCurrentView.getWebView());
                    }
                }
            });
        } else if (what == Constants.LONG_CLICK_HISTORY) {
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_delete), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    mDatabaseHandler.deleteHistoryItem(url);
                    openHistory();
                }
            });
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_delete_all), new OnSheetItemClickListener() {
                public void onClick(int which) {
                    new MarkDialog(mContext).builder().setTitle(BrowserActivity
                            .this.getResources().getString(R.string.action_delete_all)).setMessage(BrowserActivity.this
                            .getResources().getString(R.string.dialog_sure)).setPositiveButton(BrowserActivity
                            .this.getResources().getString(R.string.action_ok), new View.OnClickListener() {
                        public void onClick(View v) {
                            BrowserUtils.clearWebViewHistory(mContext);
                            openHistory();
                        }
                    }).setNegativeButton(getResources().getString(R.string.action_no),
                            null).show();
                }
            });
        }

        if (what != Constants.LONG_CLICK_BOOKMARK_FOLDER && this.mPreferences.getAdBlockEnabled()
                && this.mPreferences.getJavaScriptEnabled()) {
            sheetMenu.addSheetItem(this.getResources().getString(R.string.action_mark),
                    new OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            mCurrentView.loadUrl(JS.markAds(mContext, url));
                        }
                    });
        }

        sheetMenu.show(this.mProgressBar, this.mTouchX, this.mTouchY);
    }


    public void longClickPage(String url) {

        if (this.mCurrentView != null && this.mCurrentView.getWebView() != null) {
            WebView.HitTestResult hitResult = this.mCurrentView.getWebView().getHitTestResult();
            if (BrowserUtils.isDefaultHomePage(this.mContext, this.mCurrentView.getUrl())) {
                if (url == null) {
                    return;
                }
                if (url.startsWith("folder://")) {
                    return;
                }
                if (this.getBookmarkIdFromUrl(url) == -1) {
                    return;
                }

                this.itemLongClick(this.mBookmarkList.get(this.getBookmarkIdFromUrl(url)).getUrl(),
                        5);
                return;
            }

            //书签页面
            if (BrowserUtils.isBookmarkPage(this.mContext, this.mCurrentView.getUrl())) {
                if (url == null) {
                    return;
                }
                if ((url.startsWith("folder://")) && !url.equalsIgnoreCase("folder://")) {
                    url.substring(9);//注意这里
                    String extra = null;
                    try {
                        extra = URLDecoder.decode(url.substring(9), "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    this.itemLongClick(extra, 4);
                    return;
                }

                if (this.getBookmarkIdFromUrl(url) == -1) {
                    return;
                }

                this.itemLongClick(this.mBookmarkList.get(this.getBookmarkIdFromUrl(url)).getUrl(),
                        2);
                return;
            }
            //历史页面
            if (BrowserUtils.isHistoryPage(this.mContext, this.mCurrentView.getUrl())) {
                if (url == null) {
                    return;
                }

                this.itemLongClick(url, 3);
                return;
            }

            if (url != null) {
                if (hitResult != null) {
                    if (hitResult.getType() != WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE
                            && hitResult.getType() != WebView.HitTestResult.IMAGE_TYPE) {
                        this.itemLongClick(url, 0);
                        return;
                    }

                    this.itemLongClick(url, 1);
                    return;
                }

                this.itemLongClick(url, 0);
                return;
            }

            if (hitResult != null && hitResult.getExtra() != null) {
                String extra = hitResult.getExtra();
                if (hitResult.getType() != WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE &&
                        hitResult.getType() != WebView.HitTestResult.IMAGE_TYPE) {
                    return;
                }

                this.itemLongClick(extra, 1);
            }
        }
    }


    /**
     * @param requestCode
     * @param resultCode
     * @param intent
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Uri v1;
        if (requestCode != 911) {
            if (Build.VERSION.SDK_INT >= 21) {
                this.filePathCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode,
                        intent));
            }

            if (requestCode != 1) {
                return;
            }

            if (Constants.API >= 21) {
                return;
            }

            if (this.mUploadMessage == null) {
                return;
            }

            if (intent == null || resultCode != -1) {
                v1 = null;
            } else {
                v1 = intent.getData();
            }

            this.mUploadMessage.onReceiveValue(v1);
            this.mUploadMessage = null;
        }

    }

    /**
     * @param v
     */
    public void onBtnClick(View v) {
        switch (v.getId()) {
            case R.id.action_new_tab: {
                this.newTab(true, null);

                break;
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.screenWidthDp > newConfig.screenHeightDp) {
            this.enterPadMode();
        } else {
            this.exitPadMode();
        }

        this.mBrowserFrame.invalidate();
    }


    public void onHideCustomView() {
        if (this.mCustomView != null && this.mCustomViewCallback != null && this.mCurrentView != null
                ) {
            this.mCurrentView.setVisibility(View.VISIBLE);
            this.mCustomView.setKeepScreenOn(false);
            setFullscreen(this.mPreferences.getHideStatusBarEnabled());
            View v0 = this.getWindow().getDecorView();
            if (v0 != null) {
                ((FrameLayout) v0).removeView(this.mFullscreenContainer);
            }

            if (Constants.API < 19) {
                this.mCustomViewCallback.onCustomViewHidden();
            }

            this.mFullscreenContainer = null;
            this.mCustomView = null;
            if (this.mVideoView != null) {
                this.mVideoView.setOnErrorListener(null);
                this.mVideoView.setOnCompletionListener(null);
                this.mVideoView = null;
            }

            this.setRequestedOrientation(this.mOriginalOrientation);
            this.touchShade();
        }
    }

    /**
     * 处理返回键
     *
     * @return
     */
    private boolean onKeyCodeBack() {
        if (this.mTabWindow.getVisibility() == View.VISIBLE) {
            this.touchShade();
            return true;
        }
        if ((this.mCurrentView.isShown()) && this.mFullscreenContainer == null
                && this.mCustomView == null && this.mVideoView == null) {
            if (!BrowserUtils.isSetedHomePage(this.mContext, this.mCurrentView.getUrl())) {
                this.goBack();
            } else if (this.mCurrentView.isDestroyed()) {
            } else if (this.mWebViewList.size() == 1) {
                this.exit();
            } else {
                this.deleteTab(this.mCurrentView.getId());
            }

            return true;
        }

        this.onHideCustomView();
        return true;
    }

    private boolean onKeyCodeSearch() {
        this.operation(4);
        return true;
    }

    private boolean onKeyCodeVolumeDown() {
        boolean v0;
        if (this.mPreferences.getVolumeScroll()) {
            this.scrollWebView(3);
            v0 = true;
        } else {
            v0 = false;
        }

        return v0;
    }

    private boolean onKeyCodeVolumeUp() {
        boolean v0;
        if (this.mPreferences.getVolumeScroll()) {
            this.scrollWebView(2);
            v0 = true;
        } else {
            v0 = false;
        }

        return v0;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {//24
            if (this.mFullscreenContainer == null && this.mCustomView == null
                    && this.mVideoView == null
                    && (this.onKeyCodeVolumeUp())) {
                return true;
            }

            return false;
        }
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {//25
            if (this.mFullscreenContainer == null && this.mCustomView == null && this.mVideoView ==
                    null && (this.onKeyCodeVolumeDown())) {
                return true;
            }
            return false;
        }

        if (keyCode == KeyEvent.KEYCODE_BACK) {//4返回
            return onKeyCodeBack();
        }

        if (keyCode == KeyEvent.KEYCODE_SEARCH) {//84
            return this.onKeyCodeSearch();
        }

        return false;

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {//25
            if (this.mFullscreenContainer == null && this.mCustomView == null &&
                    this.mVideoView == null) {
                return true;
            }
            return false;
        } else {
            if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {//24
                if (this.mFullscreenContainer == null && this.mCustomView == null && this.mVideoView == null) {
                    return true;
                }
                return false;
            }
            return super.onKeyUp(keyCode, event);
        }
    }


    public void onLongPress() {
        if (this.mClickHandler == null) {
            this.mClickHandler = new ClickHandler(this.mContext);
        }

        Message message = this.mClickHandler.obtainMessage();
        if (message != null) {
            message.setTarget(this.mClickHandler);
        }

        if (this.mCurrentView.getWebView() != null) {
            this.mCurrentView.getWebView().requestFocusNodeHref(message);
        }
    }

    /**
     * 菜单按键
     *
     * @param v
     */
    public void onMenuBtnClick(View v) {
        switch (v.getId()) {
            case R.id.action_add_bookmark: {//添加标签
                this.mMenu.dismiss();
                this.addBookmark(this.mCurrentView.getTitle(), this.mCurrentView.getUrl());
                break;
            }

            case R.id.action_share: {//分享连接
                this.mMenu.dismiss();
                if (this.mCurrentView == null) {
                    return;
                }
                if (this.mCurrentView.getUrl() == null) {
                    return;
                }
                if (this.mCurrentView.getUrl().startsWith("file://")) {
                    return;
                }
                IntentUtils.share(this.mContext, this.mCurrentView.getUrl());
                break;
            }
            case R.id.action_incognito: {//无痕
                this.mMenu.dismiss();
                break;
            }
            case R.id.action_image_off: {//图片显示
                this.mMenu.dismiss();
                if (this.mPreferences.getImageSwitchEnabled()) {//当前智能无图
                    this.mPreferences.setImageSwitchEnabled(false);
                    this.mPreferences.setBlockImagesEnabled(false);
                    this.mMenuImg.setText(this.getResources().getString(R.string.image_off));
                    ViewUtils.showToast(rootLayout, this.getResources().getString(R.string.image_off));
                } else if (this.mPreferences.getBlockImagesEnabled()) {//当前无图模式
                    this.mPreferences.setImageSwitchEnabled(true);
                    this.mMenuImg.setText(this.getResources().getString(R.string.image_auto));
                    ViewUtils.showToast(rootLayout, this.getResources().getString(R.string.image_auto));
                } else {
                    this.mPreferences.setBlockImagesEnabled(true);
                    this.mMenuImg.setText(this.getResources().getString(R.string.image_on));
                    ViewUtils.showToast(rootLayout, this.getResources().getString(R.string.image_on));
                }

                this.onSettingsChanged();
                break;
            }

            case R.id.action_history: {//历史页面
                this.mMenu.dismiss();
                this.openHistory();
                break;
            }
            case R.id.action_pcview: {//电脑模式
                this.mMenu.dismiss();
                boolean isEnabled = true;
                if (this.mPreferences.getRuequstDesktopSiteEnabled()) {
                    isEnabled = false;
                }
                mPreferences.setRuequstDesktopSiteEnabled(isEnabled);
                ViewUtils.setTextActive(this.mContext, this.mMenuPC, this.mPreferences.getRuequstDesktopSiteEnabled());
                this.onSettingsChanged();
                this.mCurrentView.reload();
                break;
            }
            case R.id.action_screenshot: {//网页截图
                this.mMenu.dismiss();
                new MarkDialog(this.mContext).builder()
                        .setMessage(this.getResources().getString(R.string.web_screenshot))
                        .setPositiveButton(this.getResources().getString(R.string.screenshot_now),
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        new ScreenshotTask(mContext, mCurrentView
                                                .getWebView(), false).execute();
                                    }
                                })
                        .setNegativeButton(this.getResources().getString(R.string.screenshot_all),
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        new ScreenshotTask(mContext, mCurrentView.getWebView(), true)
                                                .execute();
                                    }
                                }).show();
                break;
            }
            case R.id.action_source: {//查看源码
                this.mMenu.dismiss();
                if (this.mCurrentView.getUrl() == null) {
                    return;
                }

                if (!this.mCurrentView.getUrl().startsWith("http://") && !this.mCurrentView.getUrl().
                        startsWith("https://")) {
                    return;
                }

                this.mCurrentView.loadUrl("javascript:alert(document.documentElement.outerHTML)");
                break;
            }
            case R.id.action_translate: {//翻译网页
                this.mMenu.dismiss();
                if (this.mCurrentView.getUrl().startsWith("file://")) {
                    return;
                }

                new MarkRadioDialog(this.mContext).builder()
                        .setTitle(this.getResources().getString(R.string.action_translate))
                        .setCancelable(true)
                        .setSingleChoiceItems(R.array.array_translate, -1,
                                new RadioGroup.OnCheckedChangeListener() {
                                    @Override
                                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                                        mCurrentView.loadUrl(JS.translate(checkedId));
                                        ViewUtils.showToast(rootLayout, mContext.getResources()
                                                .getString(R.string.toast_wait_a_minute));
                                    }
                                }).show();
                break;
            }
            case R.id.action_settings: {//浏览器设置(@Deprecated)
                this.mMenu.dismiss();
                this.startActivity(new Intent(this.mContext, GeneralSettings.class));
                break;
            }
            case R.id.action_exit: {//退出(@Deprecated)
                this.mMenu.dismiss();
                this.exit();
                break;
            }
        }
    }

    public boolean onMenuOpened(int featureId, Menu menu) {
        if (this.mFullScreen) {
            this.showOperationBar();
        }

        if (this.mMenu.isShowing()) {
            this.mMenu.dismiss();
        } else {
            this.showMenu();
        }

        return false;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        handleNewIntent(intent);
        super.onNewIntent(intent);
    }

    public void onPadBarBtnClick(View v) {
        switch (v.getId()) {
            case R.id.pad_back: {
                this.goBack();
                return;
            }
            case R.id.pad_forward: {
                this.goForward();
                return;
            }
            case R.id.pad_tab: {
                if (this.mTabWindow.getVisibility() == View.GONE) {
                    ViewUtils.showView(BrowserActivity.this, this.mToolBar, this.mBottomTransIn);
                    ViewUtils.showView(BrowserActivity.this, this.mTabWindow, this.mTopTransIn);
                } else if (this.mTabWindow.getVisibility() == View.VISIBLE) {
                    ViewUtils.hideView(BrowserActivity.this, this.mTabWindow, this.mTopTransOut);
                }
                this.setWebViewForwardColor();
                return;
            }
            case R.id.pad_options: {
                this.showMenu();
                return;
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        this.saveOpenTabs();
        if (this.mCurrentView != null) {
            this.mCurrentView.pauseTimers();
            this.mCurrentView.onPause();
        }

        if (this.mDatabaseHandler != null && (this.mDatabaseHandler.isOpen())) {
            this.mDatabaseHandler.close();
        }

        if (this.mMenu.isShowing()) {
            this.mMenu.dismiss();
        }

    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        this.doNext(requestCode, grantResults, permissions);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (this.mSearchAdapter != null) {
            this.mSearchAdapter.refreshBookmarks();
        }

        if (this.mCurrentView != null) {
            this.mCurrentView.resumeTimers();
            this.mCurrentView.onResume();
            if (this.mDatabaseHandler == null) {
                this.mDatabaseHandler = new DatabaseHandler(this.mContext);
            } else if (!this.mDatabaseHandler.isOpen()) {
                this.mDatabaseHandler = new DatabaseHandler(this.mContext);
            }

            this.mBookmarkList = this.mBookmarkManager.getBookmarks();
        } else {
            this.initialize();
        }

        this.initializePreferences();
        this.initializeWidgetPreferences();
        this.onSettingsChanged();
        this.initMenu();
    }

    public synchronized void onSettingsChanged() {
        if (this.mWebViewList != null) {
            int v0 = 0;
            while (v0 < this.mWebViewList.size()) {

                if (this.mWebViewList.get(v0) != null) {
                    this.mWebViewList.get(v0).initializePreferences(this.mWebViewList.get(v0).getWebView(),
                            this.mContext);
                } else {
                    this.mWebViewList.remove(v0);
                }

                ++v0;
            }
            return;
        }

        this.initialize();
    }

    public void onShowCustomView(View view, int requestedOrientation, WebChromeClient.CustomViewCallback
            callback) {
        if (view != null) {
            if (this.mCustomView != null && callback != null) {
                callback.onCustomViewHidden();
                return;
            }

            view.setKeepScreenOn(true);
            this.mOriginalOrientation = this.getRequestedOrientation();
            View v0 = this.getWindow().getDecorView();
            this.mFullscreenContainer = new FullscreenHolder(this.mContext);
            this.mCustomView = view;
            this.mFullscreenContainer.removeAllViews();
            this.mFullscreenContainer.addView(this.mCustomView, this.COVER_SCREEN_PARAMS);
            ((FrameLayout) v0).addView(this.mFullscreenContainer, this.COVER_SCREEN_PARAMS);
            this.setFullscreen(true);
            this.mCurrentView.setVisibility(View.GONE);
            if (((view instanceof FrameLayout)) && (((FrameLayout) view).getFocusedChild() instanceof VideoView)) {
                this.mVideoView = (VideoView) ((FrameLayout) view).getFocusedChild();
                this.mVideoView.setOnErrorListener(new VideoCompletionListener());
                this.mVideoView.setOnCompletionListener(new VideoCompletionListener());
            }

            this.mCustomViewCallback = callback;
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//0
        }
    }

    public void onTitleBarBtnClick(View v) {
        switch (v.getId()) {
            case R.id.titlebar_find: {
                this.findInPage();
                break;
            }
            case R.id.titlebar_go: {
                if (this.mSearch.hasFocus()) {
                    this.searchTheWeb(this.mSearch.getText().toString().trim());
                    return;
                }

                showMenu();//显示菜单
                break;
            }
        }
    }

    public void onToolbarBtnClick(View v) {
        switch (v.getId()) {
            case R.id.webview_shade: {
                this.touchShade();
                break;
            }
            case R.id.toolbar_back: {
                this.goBack();
                break;
            }
            case R.id.toolbar_forward: {
                this.goForward();
                break;
            }
            case R.id.toolbar_home: {
                this.goHomePage();
                break;
            }
            case R.id.toolbar_tab: {
                if (this.mTabWindow.getVisibility() == View.GONE) {
                    ViewUtils.showView(this, mToolBar, this.mBottomTransIn);
                    ViewUtils.showView(this, mTabWindow, this.mBottomTransIn);
                } else if (this.mTabWindow.getVisibility() == View.VISIBLE) {
                    ViewUtils.hideView(this, mTabWindow, this.mBottomTransOut);
                }

                this.setWebViewForwardColor();
                break;
            }
            case R.id.toolbar_refresh: {
                if (mCurrentView != null) {
                    this.mCurrentView.reload();
                }
                break;
            }
        }
    }

    public void openBookmarkPage(WebView view, String folder, boolean check) {
        String page = PageManager.getBookmarkPage(this.mContext, this.mBookmarkManager,
                folder, this.mPreferences.getBookmarksStyle());
        if (!check || (BrowserUtils.isLocalPage(view.getUrl()))) {
            view.loadUrl(page);
        } else {
            this.newTab(true, page);
        }
    }

    public void openDefaultHomepage(final FastView view) {
        if (view != null) {
            new Thread(new Runnable() {
                public void run() {
                    view.loadUrl(PageManager.getHomePage(mContext, BrowserActivity
                            .this.mSearchText, mPreferences.getHomepage().startsWith(
                            "about:links"), mBookmarkManager));
                }
            }).run();
        }
    }

    public void openFileChooser(ValueCallback callback) {
        this.mUploadMessage = callback;
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.addCategory("android.intent.category.OPENABLE");
        intent.setType("*/*");
        startActivityForResult(Intent.createChooser(intent, this.getString(R.string.title_file_chooser)), 1);
    }

    private void openHistory(final FastView fastView) {
        if (fastView != null) {
            new Thread(new Runnable() {
                public void run() {
                    fastView.loadUrl(PageManager.getHistoryPage(mContext));
                }
            }).run();
        }
    }

    public void openHistory() {
        new Thread(new Runnable() {
            public void run() {
                if (mCurrentView.getUrl() == null || !mCurrentView
                        .getUrl().startsWith("file://")) {
                    newTab(true, PageManager.getHistoryPage(BrowserActivity.this
                            .mContext));
                } else {
                    mCurrentView.loadUrl(PageManager.getHistoryPage(BrowserActivity
                            .this.mContext));
                }

                mSearch.setText("");
            }
        }).run();
    }

    /**
     * 输入法键盘调整
     *
     * @param i
     */
    private void operateIME(int i) {
        InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);
        if (i == 0) {
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);// 2, 0
        } else if (i == 1) {
            inputMethodManager.hideSoftInputFromWindow(mBrowserFrame.getWindowToken(), 0);//0
        }
    }

    /**
     * caozuo
     *
     * @param i
     */
    private void operation(int i) {

        switch (i) {
            case 1: {
                this.mCurrentView.reload();
                return;
            }
            case 2: {
                this.scrollWebView(0);
                return;
            }
            case 3: {
                this.scrollWebView(1);
                return;
            }
            case 4: {
                this.showOperationBar();
                this.mSearch.requestFocus();
                this.operateIME(0);
                return;
            }
            case 5: {
                this.newTab(true, null);
                return;
            }
            case 6: {
                this.addBookmark(this.mCurrentView.getTitle(), this.mCurrentView.getUrl());
                return;
            }
            case 7: {
                this.openBookmarkPage(this.mCurrentView.getWebView(), null, true);
                return;
            }
            case 8: {
                this.openHistory();
                return;
            }
            case 9: {
                this.deleteTab(this.mCurrentView.getId());
                return;
            }
            case 10: {
                int v0 = this.mIdList.indexOf(this.mCurrentView.getId());
                if (v0 - 1 >= 0) {
                    this.showTab(this.mWebViewList.get(v0 - 1));
                    return;
                }

                if (this.mIdList.size() - 1 <= 0) {
                    return;
                }

                this.showTab(this.mWebViewList.get(this.mIdList.size() - 1));
                return;
            }
            case 11: {
                int v1 = this.mIdList.indexOf(this.mCurrentView.getId());
                if (v1 <= this.mIdList.size() - 2) {
                    this.showTab(this.mWebViewList.get(v1 + 1));
                    return;
                }

                if (this.mIdList.size() - 1 <= 0) {
                } else {
                    this.showTab(this.mWebViewList.get(0));
                    return;
                }
                return;
            }
            case 12: {
                this.mCurrentView.goBack();
                return;
            }
            case 13: {
                this.mCurrentView.goForward();
                return;
            }
        }

    }

    private void readerMode(WebView view) {
        view.loadUrl(JS.runCustomCSS("img, form, iframe, ins, hr, header, footer, nav, menu, .set, .nr_set, .search, .header, .head, .footer, .foot, .position, .nav_read, .nav, .report {display: none !important}"));
        view.loadUrl(JS.deleteTags("script, style, link, img, form, iframe, ins, hr, header, footer, nav, menu, .set, .nr_set, .search, .header, .head, .footer, .foot, .position, .nav_read, .nav, .report"));
        view.loadUrl(JS.runCustomCSS("ul,dl,ol,table,.nr_page{display: none !important} html,body{width: 100% !important; max-width: 100% !important;padding:0px!important;margin:0px!important;overflow-x: hidden;} body{padding:0px !important;} div{font-size: 18px!important; line-height: 24px!important;letter-spacing:0px!important;word-wrap: break-word!important;} h1{font-size: 24px!important; text-align: center!important; letter-spacing:0px!important;}"));
    }

    public synchronized void recordAds(final String url, final String tag) {
        Log.e(BrowserActivity.class.getSimpleName(), "" +
                "标记广告:" + url + " - " + tag);
        if (url != null) {
            if (!url.isEmpty() && !url.startsWith("file://")) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (mDatabaseHandler == null) {
                                mDatabaseHandler = new DatabaseHandler(mContext);
                            } else if (!mDatabaseHandler.isOpen()) {
                                mDatabaseHandler = new DatabaseHandler(mContext);
                            }

                            if (tag.contains(",")) {
                                mDatabaseHandler.visitAdsItem(url, tag, true);
                            } else {
                                mDatabaseHandler.visitAdsItem(url, tag, false);
                            }

                        } catch (NullPointerException | SQLiteException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
    }

    private synchronized void renameFolder(final String ex_folder) {
        new MarkEditDialog(this.mContext).builder().setTitle(this.getResources().getString(R.string.title_edit_folder))
                .setCanceledOnTouchOutside(true).setOtherHint(this.getResources().getString(R.string.hint_folder),
                ex_folder, this.mBookmarkManager.getFolders()).setPositiveButton(this.getResources()
                .getString(R.string.action_ok), new MarkEditDialog.OnCustomDialogListener() {
            public void back(String title, String msg, String folder) {
                mBookmarkManager.renameFolder(ex_folder, folder);
                openBookmarkPage(mCurrentView.getWebView(),
                        null, true);
                mBookmarkList = mBookmarkManager.getBookmarks();
            }
        }).show();
    }

    private void restoreOrNewTab() {
        if (!this.mPreferences.getRestoreLostTabsEnabled()) {
            this.newTab(true, null);
            return;
        }

        if (this.mPreferences.getMemoryUrl().isEmpty()) {
            this.newTab(true, null);
            return;
        }
        if (BrowserUtils.isWifiConnected(this.mContext)) {
            this.restoreTabs();
            return;
        }
        this.newTab(true, null);
        new SuperActivityToast(this.mActivity, this.mActivity.getResources().getString(R.string.msg_restore),
                this.mActivity.getResources().getString(R.string.action_ok), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                restoreTabs();
            }
        });


    }

    private synchronized void restoreTabs() {
        int v3_1;
        String v2 = this.mPreferences.getMemoryUrl();
        this.mPreferences.setMemoryUrl("");
        String[] v1 = BrowserActivity.getArray(v2);
        int v4 = v1.length;
        v3_1 = 0;
        while (true) {

            if (v3_1 >= v4) {
                return;
            }

            String v0 = v1[v3_1];
            if (v0.length() > 0) {
                this.newTab(true, v0);
            }

            ++v3_1;
        }
    }

    private synchronized void saveOpenTabs() {
        if (!this.mWebViewList.isEmpty()) {
            StringBuilder v1 = new StringBuilder();
            int v0;
            for (v0 = 0; v0 < this.mWebViewList.size(); ++v0) {
                if (this.mWebViewList.get(v0).getUrl() != null && !BrowserUtils.isSetedHomePage(this
                        .mContext, this.mWebViewList.get(v0).getUrl()) && !this.mWebViewList.get(
                        v0).getUrl().startsWith("file://")) {
                    v1.append(this.mWebViewList.get(v0).getUrl()).append("|$|SEPARATOR|$|");
                }
            }

            this.mPreferences.setMemoryUrl(v1.toString());
        }

        return;
    }

    private void scrollWebView(int what) {
        ObjectAnimator v0;
        int[] v7;
        int v11 = R.integer.anim_time;
        int v9 = 2;
        FastView v3 = this.mCurrentView.getWebView();
        int v2 = ((WebView) v3).getMeasuredHeight();
        int v4 = ((WebView) v3).getScrollY();
        int v5 = ((int) ((((float) ((WebView) v3).getContentHeight())) * ViewUtils.getDensity(this.mContext)
                - (((float) v2)) - (((float) v4))));
        switch (what) {
            case 0: {
                if (this.mPreferences.getAnimEnabled()) {
                    v7 = new int[v9];
                    v7[0] = v4;
                    v7[1] = 0;
                    v0 = ObjectAnimator.ofInt(v3, "scrollY", v7);
                    v0.setDuration(((long) this.mContext.getResources().getInteger(v11)));
                    v0.start();
                    return;
                }

                ((WebView) v3).scrollTo(((int) ((WebView) v3).getX()), 0);
                return;
            }
            case 1: {
                if (this.mPreferences.getAnimEnabled()) {
                    v7 = new int[v9];
                    v7[0] = v4;
                    v7[1] = ((int) ((((float) ((WebView) v3).getContentHeight())) * ViewUtils.getDensity(this.mContext)));
                    v0 = ObjectAnimator.ofInt(v3, "scrollY", v7);
                    v0.setDuration(((long) this.mContext.getResources().getInteger(v11)));
                    v0.start();
                    return;
                }

                ((WebView) v3).scrollTo(((int) ((WebView) v3).getX()), ((int) ((((float) ((WebView) v3).getContentHeight()))
                        * ViewUtils.getDensity(this.mContext))));
                return;
            }
            case 2: {
                int v1 = Math.min(v2 - 50, v4);
                if (this.mPreferences.getAnimEnabled()) {
                    v7 = new int[v9];
                    v7[0] = v4;
                    v7[1] = v4 - v1;
                    v0 = ObjectAnimator.ofInt(v3, "scrollY", v7);
                    v0.setDuration(((long) this.mContext.getResources().getInteger(v11)));
                    v0.start();
                    return;
                }

                ((WebView) v3).scrollTo(((int) ((WebView) v3).getX()), v4 - v1);
                return;
            }
            case 3: {
                int v1 = Math.min(v2 - 50, v5);
                if (this.mPreferences.getAnimEnabled()) {
                    v7 = new int[v9];
                    v7[0] = v4;
                    v7[1] = v4 + v1;
                    v0 = ObjectAnimator.ofInt(v3, "scrollY", v7);
                    v0.setDuration(((long) this.mContext.getResources().getInteger(v11)));
                    v0.start();
                } else {
                    ((WebView) v3).scrollTo(((int) ((WebView) v3).getX()), v4 + v1);
                }
                return;
            }
        }

        return;
    }

    public synchronized void searchText() {

        this.runOnUiThread(new Runnable() {
            public void run() {
                operation(4);
            }
        });

    }

    /**
     * 扫码返回
     *
     * @param query
     */
    private void searchTheWeb(String query) {
        if (query.isEmpty()) {
            this.touchShade();
            return;
        }

        this.mCurrentView.stopLoading();
        if (BrowserUtils.isURL(query)) {

            this.mCurrentView.loadUrl(BrowserUtils.fixUrl(query));
            this.mPreferences.setLinksTimes(this.mPreferences.getLinksTimes() + 1);
            this.touchShade();
            return;
        }

        try {
            query = URLEncoder.encode(query, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.mCurrentView.loadUrl(mSearchText + query);
        this.mPreferences.setSearchTimes(this.mPreferences.getSearchTimes() + 1);
        if ((this.mPreferences.getSearchHintEnabled()) && !Locale.getDefault().getCountry().equalsIgnoreCase(
                "cn") && this.mPreferences.getSearchChoice() != 2 && this.mPreferences.getSearchChoice()
                != 0) {
            new SuperActivityToast(this.mActivity, this.mActivity.getResources().getString(R.string.msg_setgoogle),
                    this.mActivity.getResources().getString(R.string.action_ok), new View.OnClickListener() {
                public void onClick(View view) {
                    mPreferences.setSearchHintEnabled(false);
                    mPreferences.setSearchChoice(2);
                    mSearchText = Constants.GOOGLE_SEARCH;
                }
            }, new View.OnClickListener() {
                public void onClick(View view) {
                    mPreferences.setSearchHintEnabled(false);
                }
            });
        }


        this.touchShade();
    }

    @SuppressLint(value = {"InlinedApi"})
    private void setFullscreen(boolean enabled) {
        int v6 = 16;
        Window v1 = this.getWindow();
        WindowManager.LayoutParams v2 = v1.getAttributes();
        if (enabled) {
            v2.flags |= 1024;
            if (Constants.API >= 19) {
                v1.getDecorView().setSystemUiVisibility(5894);
            } else if (Constants.API >= v6) {
                v1.getDecorView().setSystemUiVisibility(1798);
            }
        } else {
            v2.flags &= -1025;
            if (Constants.API >= 14) {
                if (this.mCustomView != null) {
                    this.mCustomView.setSystemUiVisibility(0);
                } else {
                    this.mBrowserFrame.setSystemUiVisibility(0);
                }
            }

            if (Constants.API < v6) {
            } else {
                v1.getDecorView().setSystemUiVisibility(1792);
            }
        }

        v1.setAttributes(v2);
    }

    private void setIsFinishedLoading() {
        this.mForward.setImageResource(R.drawable.toolbar_forward);
        this.mPadForward.setImageResource(R.drawable.toolbar_forward);
    }

    private void setIsLoading() {
        this.mForward.setImageResource(R.drawable.toolbar_stop);
        this.mPadForward.setImageResource(R.drawable.toolbar_stop);
    }

    /**
     *
     */
    private void setWebViewForwardColor() {
        int v0 = this.mTabWindow.getVisibility() == View.VISIBLE ? 1 : 0;
        if ((v0 | (this.mSearch.hasFocus() ? 1 : 0)) != 0) {
            ViewUtils.showView(this, mShade, mFadeIn);
        } else {
            ViewUtils.hideView(this, mShade, mFadeOut);
        }
    }

    public void hideShadeView() {
        ViewUtils.hideView(this, mShade, this.mFadeOut);
    }

    public void showShadeView() {
        ViewUtils.showView(this, mShade, this.mFadeIn);
    }

    /**
     * @param callback
     * @param fileChooserParams
     */
    public void showFileChooser(ValueCallback callback, WebChromeClient.FileChooserParams
            fileChooserParams) {
        if (Build.VERSION.SDK_INT >= 21) {
            this.filePathCallback = callback;
            try {
                this.startActivityForResult(fileChooserParams.createIntent(), 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void showMenu() {
        this.operateIME(1);
        ViewUtils.showView(this, mUrlBar, this.mTopTransIn);
        ViewUtils.showView(this, mToolBar, this.mBottomTransIn);
        ViewUtils.hideView(this, mTabWindow, this.mBottomTransOut);
        ViewUtils.hideView(this, mShade, this.mFadeOut);
        if (this.mPadMode) {
            this.mMenu.showAsDropDown(this.findViewById(R.id.pad_options));
        } else {
            this.mMenu.showAtLocation(findViewById(R.id.urlBar), Gravity.RIGHT | Gravity.TOP, 0, 0);
        }

        ViewUtils.dimBackground(BrowserActivity.this, 1.0f, 0.5f);
    }

    /**
     *
     */
    public void showOperationBar() {
        if (this.mUrlBar.getVisibility() != View.VISIBLE && (this.mFullScreen)) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(this.mBrowserFrame, "translationY", new float
                    []{0f, this.mUrlBarHeight});
            if (this.mPreferences.getAnimEnabled()) {
                animator.setDuration(((long) this.mContext.getResources().getInteger(R.integer.anim_time)));
            } else {
                animator.setDuration(0);
            }

            animator.setInterpolator(new AccelerateInterpolator());
            animator.start();
            ViewUtils.showView(this, mUrlBar, this.mTopTransIn);
            ViewUtils.showView(this, mToolBar, this.mBottomTransIn);
        }
    }

    public synchronized void showSelectedTab(int id) {

        int v1 = this.mIdList.indexOf(id);
        int v0 = this.mIdList.indexOf(this.mCurrentView.getId());
        if (v1 != -1 && v0 != v1) {
            this.showTab(this.mWebViewList.get(v1));
        }

        this.touchShade();
    }

    private synchronized void showTab(BrowserView view) {
        if (view != null) {

            if (this.mCurrentView != null) {
                this.mBrowserFrame.removeView(this.mCurrentView.getMainView());
                this.mCurrentView.deactivateTab();
            }

            this.mBrowserFrame.addView(view.getMainView());
            this.mCurrentView = view;
            this.mCurrentView.activateTab();
            if (this.mCurrentView != null) {
                this.mCurrentView.requestFocus();
            }

            this.updateProgress(view.getProgress());
            this.updateUrlBox(view.getUrl(), view.getTitle(), false, false);
            this.updateColor(view.getWebColor());

        }

    }

    /**
     * 全屏
     */
    private void switchFullScreenMode() {

        this.mUrlBarHeight = Constants.API < 19 || Constants.API >= 21 ||
                (this.mPreferences.getHideStatusBarEnabled())
                ? this.mContext.getResources().getDimensionPixelSize(R.dimen.top_bar_height) :
                this.mContext.getResources().getDimensionPixelSize(R.dimen.top_bar_height) +
                        BrowserActivity.getStatusBarHeight(this.mContext);
        if (this.mPreferences.getHideStatusBarEnabled()) {
            this.getWindow().setFlags(1024, 1024);
            this.mFullScreen = true;
        } else {
            this.getWindow().clearFlags(1024);
            this.mFullScreen = this.mPreferences.getFullScreenEnabled();
        }

        if ((this.mPreferences.getHideStatusBarEnabled()) || (this.mPreferences.getFullScreenEnabled())
                ) {
            this.mBrowserFrame.setLayoutParams(new RelativeLayout.LayoutParams(-1, -1));
            if (this.mUrlBar.getVisibility() == View.VISIBLE) {
                FrameLayout v3 = this.mBrowserFrame;
                float[] v5 = new float[2];
                v5[0] = 0f;
                v5[1] = ((float) this.mUrlBarHeight);
                ObjectAnimator.ofFloat(v3, "translationY", v5).setDuration(0).start();
            }
        } else {
            ViewUtils.showView(this, mUrlBar, this.mTopTransIn);
            ViewUtils.showView(this, mToolBar, this.mBottomTransIn);
            ObjectAnimator.ofFloat(this.mBrowserFrame, "translationY", new float[]{0f, 0f}).setDuration(
                    0).start();
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);//-1 , -1
            lp.addRule(3, R.id.urlBar);
            lp.addRule(2, R.id.toolBar);
            this.mBrowserFrame.setLayoutParams(lp);
        }


        if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21 &&
                !this.mPreferences.getHideStatusBarEnabled()) {
            this.mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//67108864
            ViewGroup.LayoutParams lp = this.mUrlBar.getLayoutParams();
            lp.height = this.mUrlBarHeight;
            this.mUrlBar.setLayoutParams(lp);
            this.mUrlBar.setPadding(0, BrowserActivity.getStatusBarHeight(this.mContext), 0, 0);
            ViewGroup root = (ViewGroup) ((ViewGroup) this.mActivity.findViewById(android.R.id.content))//16908290
                    .getChildAt(0);
            root.setFitsSystemWindows(false);
            root.setClipToPadding(true);
            if (this.mStatusBarView == null) {
                this.mStatusBarView = new View(this.mActivity);
                this.mStatusBarView.setLayoutParams(new LinearLayout.LayoutParams(-1, BrowserActivity
                        .getStatusBarHeight(this.mContext)));
                this.mStatusBarView.setBackgroundColor(this.getResources().getColor(R.color.back_color_dark));
                root.addView(this.mStatusBarView);
            } else {
                this.mStatusBarView.setVisibility(View.VISIBLE);
            }
        } else if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
            this.mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//67108864
            ViewGroup.LayoutParams lp = this.mUrlBar.getLayoutParams();
            lp.height = this.mUrlBarHeight;
            this.mUrlBar.setLayoutParams(lp);
            this.mUrlBar.setPadding(0, 0, 0, 0);
            ViewGroup root = (ViewGroup) ((ViewGroup) this.mActivity.findViewById(android.R.id.content))//16908290
                    .getChildAt(0);
            if (Constants.API >= 14) {
                root.setFitsSystemWindows(true);
            }

            root.setClipToPadding(true);
            if (this.mStatusBarView == null) {
                return;
            }

            this.mStatusBarView.setVisibility(View.GONE);
        }
    }


    private void touchShade() {
        this.operateIME(1);
        if (this.mCurrentView != null) {
            this.mCurrentView.requestFocus();
        }

        if (this.mPadMode) {
            ViewUtils.hideView(this, mTabWindow, this.mTopTransOut);
        } else {
            ViewUtils.hideView(this, mTabWindow, this.mBottomTransOut);
        }

        this.setWebViewForwardColor();
    }

    public void update(String url) {
        if (this.getBookmarkIdFromUrl(url) != -1) {
            int id = this.getBookmarkIdFromUrl(url);
            this.mBookmarkList.get(id).setOrder(this.mBookmarkList.get(id).getOrder() + 1);
            this.mBookmarkManager.overwriteBookmarks(this.mBookmarkList);
        }
    }

    public void updateColor(int webColor) {
        if (webColor == -1) {
            webColor = -1;
        }

        if (this.mBackground.getColor() != webColor && !this.mPreferences.getNightModeEnabled() && (this
                .mPreferences.getColorModeEnabled())) {
            this.changeColor(webColor);
        }
    }

    public void updateHistory(String title, String url) {
        if (!this.mPreferences.getIncognitoModeEnabled() && title != null && url != null) {
            this.addItemToHistory(title, url);
        }
    }

    /**
     * 刷新进度
     *
     * @param n
     */
    public void updateProgress(int n) {
        ObjectAnimator objectAnimator;
        n += 20;
        if (n > this.mProgressBar.getProgress()) {
            if (this.mPreferences.getAnimEnabled()) {
                objectAnimator = ObjectAnimator.ofInt(this.mProgressBar, "progress", new int[]{n});
                objectAnimator.setDuration(((long) (this.mContext.getResources().getInteger(R.integer.anim_time) / 3)));
                objectAnimator.setInterpolator(new DecelerateInterpolator());
                objectAnimator.start();
            } else {
                this.mProgressBar.setProgress(n);
            }
        } else if (n < this.mProgressBar.getProgress()) {
            if (this.mPreferences.getAnimEnabled()) {
                objectAnimator = ObjectAnimator.ofInt(this.mProgressBar, "progress", new int[]{0, n});
                objectAnimator.setDuration(((long) (this.mContext.getResources().getInteger(R.integer.anim_time) / 3)));
                objectAnimator.setInterpolator(new DecelerateInterpolator());
                objectAnimator.start();
            } else {
                this.mProgressBar.setProgress(n);
            }
        }

        if (n >= 100) {
            this.mProgressBar.setProgress(100);
            ViewUtils.hideView(this, mProgressBar, this.mFadeOut);
            this.setIsFinishedLoading();
        } else {
            ViewUtils.showView(this, mProgressBar, this.mFadeIn);
            this.setIsLoading();
        }
    }


    public void updateUrlBox(String url, String title, Boolean focus, Boolean loading) {
        if (!this.mSearch.hasFocus() || (TextUtils.isEmpty(this.mSearch.getText()))) {
            if (url != null) {
                if (TextUtils.isEmpty(title)) {
                    title = url;
                }
            } else {
                url = " ";
                title = this.mContext.getString(R.string.untitled);
            }

            if (focus) {
                if (!BrowserUtils.isSetedHomePage(this.mContext, url)
                        && !url.startsWith("file://" + mContext.getFilesDir().getPath())) {
                    this.mSearch.setText(url);
                } else {
                    this.mSearch.setText(" ");
                }
            } else {
                this.mSearch.setText("");
                if (loading) {
                    if (url.startsWith("file://")) {

                    } else if (this.mPreferences.getUrlBoxChoice() == 2) {
                        this.mSearch.setHint(BrowserUtils.getDomainName(url));
                    } else {
                        this.mSearch.setHint(url);
                    }
                } else {
                    switch (this.mPreferences.getUrlBoxChoice()) {
                        case 0: {
                            this.mSearch.setHint(title);
                            break;
                        }
                        case 1: {
                            if (url.startsWith("file://")) {
                                this.mSearch.setHint(title);
                                break;
                            }

                            this.mSearch.setHint(url);
                            break;
                        }
                        case 2: {
                            if (url.startsWith("file://")) {
                                this.mSearch.setHint(title);
                                break;
                            }

                            this.mSearch.setHint(BrowserUtils.getDomainName(url));
                            break;
                        }
                    }

                }
            }

            if (url.startsWith("https://")) {
                this.mSaveState.setImageResource(R.drawable.titlebar_lock);
            } else {
                this.mSaveState.setImageResource(R.drawable.titlebar_search);
            }


            if (focus) {
                return;
            }

            mMenuOrForward.setImageResource(R.drawable.toolbar_menu);
        }
    }
}

